<template>
    <div>
        <el-row class="home" :gutter="20">
            <el-col :span="15">
                <el-card shadow="hover">
                    <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px"
                        class="demo-ruleForm">
                        <el-form-item>
                            <el-upload class="avatar-uploader" action="http://localhost:9000/common/upload/"
                                :show-file-list="false" :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload">
                                <img v-if="ruleForm.image" :src="'http://localhost:9000/common/download?name='+ruleForm.image" class="avatar">
                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            </el-upload>

                        </el-form-item>
                        <el-form-item label="用户名" prop="username">
                            <el-input type="username" v-model="ruleForm.username" autocomplete="off"></el-input>
                        </el-form-item>
                        <el-form-item label="年龄" prop="age">
                            <el-input v-model.number="ruleForm.age"></el-input>
                        </el-form-item>
                        <el-form-item label="电话" prop="phone">
                            <el-input v-model="ruleForm.phone"></el-input>
                        </el-form-item>
                        <el-form-item label="密码" prop="pass">
                            <el-input type="password" v-model="ruleForm.password" autocomplete="off"></el-input>
                        </el-form-item>
                        <el-form-item label="确认密码" prop="checkPass">
                            <el-input type="password" v-model="ruleForm.password" autocomplete="off"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="submitForm(ruleForm)">提交</el-button>
                            <el-button @click="resetForm()">返回</el-button>
                        </el-form-item>
                    </el-form>
                </el-card>
            </el-col>
        </el-row>
        <el-row>
        </el-row>
    </div>
</template>

<script>
import { updateUser } from '@/api/user'
export default {
    name: 'UserUpdate',
    data() {
        var checkAge = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('年龄不能为空'));
            }
            setTimeout(() => {
                if (!Number.isInteger(value)) {
                    callback(new Error('请输入数字值'));
                } else {
                    if (value < 18) {
                        callback(new Error('必须年满18岁'));
                    } else {
                        callback();
                    }
                }
            }, 1000);
        };
        var validatePass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入密码'));
            } else {
                if (this.ruleForm.checkPass !== '') {
                    this.$refs.ruleForm.validateField('checkPass');
                }
                callback();
            }
        };
        var validatePass2 = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'));
            } else if (value !== this.ruleForm.pass) {
                callback(new Error('两次输入密码不一致!'));
            } else {
                callback();
            }
        };
        return {
            opts: [{
                label: '男',
                value: 1
            },
            {
                label: '女',
                value: 0
            }],
            ruleForm: {
            },
            rules: {
                pass: [
                    { validator: validatePass, trigger: 'blur' }
                ],
                checkPass: [
                    { validator: validatePass2, trigger: 'blur' }
                ],
                age: [
                    { validator: checkAge, trigger: 'blur' }
                ]
            }
        };
    },
    methods: {
        handleAvatarSuccess(res, file) {
        this.ruleForm.image =res.data
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
        submitForm(formName) {


 this.$confirm('修改完个人信息需重新登录，是否修改个人信息？', '确认信息', {
          distinguishCancelAndClose: true,
          confirmButtonText: '保存',
          cancelButtonText: '放弃修改'
        })
          .then(() => {
            updateUser(formName).then(res=>{
                if(res.data.code===1){
                        this.isShow=false
                        this.$message.success("修改成功")
                        localStorage.removeItem('userInfo')
                         localStorage.removeItem('token')
                        this.$router.push('/')
                    }else{
                        this.isShow = false
                        this.$message.error(res.msg || '操作失败')
                    }
                }).catch(err=>{
                    this.$message.error('请求出错了：'+err)
                    this.isShow = false
                })
          })
          .catch(action => {
            this.$message({
              type: 'info',
              message: action === 'cancel'
                ? '放弃保存并离开页面'
                : '停留在当前页面'
            })
          });
        },
        resetForm() {
            this.$router.back()
        },
        usermation() {
            this.ruleForm = JSON.parse(localStorage.getItem('userInfo'))
            console.log(this.ruleForm);
        }
    },
    mounted() {
        this.usermation()
    },
}

</script>


<style scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    border:5px dashed green;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>